﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraLayout;
using DevExpress.XtraEditors.Controls;
using PMS.Entity;
//using FptSoftware.Framework.Common;
//using FptSoftware.Framework.SysSetting;
using PMS.Resources;
using PMS.Utils;
using PMS.Exceptions;
using System.Windows.Forms;

namespace PMS.Win
{
    public partial class BaseForm : XtraForm
    {
        #region Constructors
        protected bool m_isImporting = false;
        public string functionID = null;
        public BaseForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Fields and Properties

        public static Account CurrentUser
        {
            get;
            set;
        }

        public static bool IsLoggedIn { get; set; }

        public bool ForceClose { get; set; }

        [Browsable(false)]
        public string CurrentUserName
        {
            get
            {
                if (CurrentUser != null)
                {
                    return CurrentUser.Hoten;
                }
                return Environment.UserName;
            }
        }

        public DXValidationProvider ValidationProvider
        {
            get
            {
                return this.dxValidationProvider;
            }
        }

        public bool ForceToValidate { get; set; }

        #endregion

        #region Public Methods

        /// <summary>
        /// Creates a validation rule for required fields.
        /// </summary>
        /// <returns>A require validation rule.</returns>
        public ValidationRule CreateNotEmptyValidationRule()
        {
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = Messages.GetString("GEN_REQUIRED_FIELD");
            return notEmptyValidationRule;
        }

        /// <summary>
        /// Creates a validation rule for fields whose values have to be in a specific range.
        /// </summary>
        /// <param name="lowerBound">The lower bound. Applied field's value has to be greater than this value.</param>
        /// <param name="upperBound">The upper bound. Applied field's value has to be less than this value.</param>
        /// <returns>A range validation rule.</returns>
        public ValidationRule CreateRangeValidationRule(object lowerBound, object upperBound)
        {
            ConditionValidationRule rangeValidationRule = new ConditionValidationRule();
            rangeValidationRule.ConditionOperator = ConditionOperator.Between;
            rangeValidationRule.Value1 = lowerBound;
            rangeValidationRule.Value2 = upperBound;
            rangeValidationRule.ErrorText =
              string.Format(Messages.GetString("ValidationErrorNotInRange"), lowerBound, upperBound);
            return rangeValidationRule;
        }

        /// <summary>
        /// Creates a validation rule for fields that are required to contain a specific value.
        /// </summary>
        /// <param name="containingObject">The value which is required to be presented in the field.</param>
        /// <returns>A containing validation rule.</returns>
        public ValidationRule CreateContainsValidationRule(object containingObject)
        {
            ConditionValidationRule containsValidationRule = new ConditionValidationRule();
            containsValidationRule.ConditionOperator = ConditionOperator.Contains;
            containsValidationRule.Value1 = containingObject;
            containsValidationRule.ErrorText = Messages.GetString("ValidationErrorNotContainValue");
            containsValidationRule.ErrorType = ErrorType.Warning;
            return containsValidationRule;
        }

        /// <summary>
        /// Creates a validation rule that compares the field to a specified value.
        /// </summary>
        /// <param name="comparingObject">The value to be compared with.</param>
        /// <returns>A comparing validation rule.</returns>
        public ValidationRule CreateNotEqualsValidationRule(object comparingObject)
        {
            ConditionValidationRule notEqualsValidationRule = new ConditionValidationRule();
            notEqualsValidationRule.ConditionOperator = ConditionOperator.NotEquals;
            notEqualsValidationRule.Value1 = comparingObject;
            notEqualsValidationRule.ErrorText = Messages.GetString("ValidationErrorEqualsTo");
            //notEqualsValidationRule.ErrorType = ErrorType.Information;
            notEqualsValidationRule.ErrorType = ErrorType.Default;
            return notEqualsValidationRule;
        }

        /// <summary>
        /// Creates a validation rule that requires the applying control equals to a specified control.
        /// </summary>
        /// <param name="comparingControl">The <see cref="Control"/> to be compared with.</param>
        /// <returns>A comparing validation rule.</returns>
        public ValidationRule CreateCompareAgainstControlValidationRule(Control comparingControl)
        {
            CompareAgainstControlValidationRule compareValidationRule = new CompareAgainstControlValidationRule();
            compareValidationRule.Control = comparingControl;
            compareValidationRule.CompareControlOperator = CompareControlOperator.Equals;
            compareValidationRule.ErrorText =
              string.Format(Messages.GetString("ValidationErrorNotEqualToControl"), comparingControl);
            compareValidationRule.CaseSensitive = true;
            return compareValidationRule;
        }

        public ValidationRule CreateCustomValidationRule()
        {
            CustomValidationRule customValidationRule = new CustomValidationRule();
            customValidationRule.ErrorText = "Please enter a valid person name";
            customValidationRule.ErrorType = ErrorType.Warning;
            return customValidationRule;
        }

        public ValidationRule CreateGreaterOrEqualValidationRule(object comparingObject)
        {
            //CompareAgainstControlValidationRule greaterValidationRule = new CompareAgainstControlValidationRule();
            //greaterValidationRule.Control = comparingControl;
            //greaterValidationRule.CompareControlOperator = CompareControlOperator.GreaterOrEqual;
            //greaterValidationRule.ErrorText = string.Format(Messages.GetString("ValidationNotGreater"), lblComparingControl);
            //return greaterValidationRule;

            ConditionValidationRule notEqualsValidationRule = new ConditionValidationRule();
            notEqualsValidationRule.ConditionOperator = ConditionOperator.GreaterOrEqual;
            notEqualsValidationRule.Value1 = comparingObject;
            notEqualsValidationRule.ErrorText = string.Format(Messages.GetString("ValidationErrorGreater"), string.Format("{0:" + ConfigurationConstant.PositiveCurrencyFormatString + "}", comparingObject));
            notEqualsValidationRule.ErrorType = ErrorType.Critical;
            return notEqualsValidationRule;
        }

        /// <summary>
        /// Check the specified control whether pass the validation or not
        /// </summary>
        /// <param name="control">the control to check</param>
        /// <returns></returns>
        protected bool IsValidControl(Control control)
        {
            if (control != null && validators.ContainsKey(control))
            {
                Validator validator = validators[control];
                if (validator != null)
                {
                    return validator.Validate();
                }
            }
            return true;
        }

        public class CustomValidationRule : ValidationRule
        {
            public override bool Validate(Control control, object value)
            {
                string str = (string)value;
                string[] values = new string[] { "Dr.", "Mr.", "Mrs.", "Miss", "Ms." };
                bool res = false;
                foreach (string val in values)
                {
                    if (ValidationHelper.Validate(str, ConditionOperator.BeginsWith, val, null, null, false))
                    {
                        string name = str.Substring(val.Length);
                        if (name.Trim().Length > 0) res = true;

                        this.ErrorText = "???";
                        //this.ErrorType =
                    }
                }
                return res;
            }
        }

        public void ResetValidator()
        {
            RemoveControlError();
            RemoveTabControlError();
            validators.Clear();
        }

        public bool ValidateControls()
        {
            bool valid = true;
            bool hasError = false;
            bool isSkipAllControl = true;
            Control FirstControlError = null;
            int count = 0;
            RemoveTabControlError();

            if (validators.Count == 0)
                return true;

            count = validators.Keys.Count;
            if (count > 0)
            {
                foreach (Control control in validators.Keys)
                {
                    if ((control as TextEdit).Properties.ReadOnly == false)
                    {
                        isSkipAllControl = false;
                        Control controlNeedValidating = control;
                        Validator v = validators[controlNeedValidating];
                        this.dxValidationProvider.RemoveControlError(controlNeedValidating);
                        v.ControlNeedValidating = controlNeedValidating;
                        valid = v.Validate();
                        if (!valid)
                        {
                            hasError = true;
                            if (FirstControlError == null)
                            {
                                FirstControlError = control;
                            }
                        }
                    }
                }
            }
            if (isSkipAllControl == true)
                return true;

            if (FirstControlError != null)
            {
                XtraTabPage xtraTabPageParent = FindXtraTabPageParent(FirstControlError);
                if (xtraTabPageParent != null)
                {
                    XtraTabControl tabControl = (xtraTabPageParent.Parent as XtraTabControl);
                    tabControl.SelectedTabPage = xtraTabPageParent;
                }
                FirstControlError.Focus();
            }

            return !hasError;
        }
        public void SetTabControlValidateError(Control control, bool isError)
        {
            XtraTabPage xtraTabPageParent = FindXtraTabPageParent(control);
            if (xtraTabPageParent == null)
            {
                return;
            }
            ForceToValidate = false;
            if (isError == false)
            {
                if (xtraTabPageParent.PageEnabled)
                {
                    xtraTabPageParent.Appearance.Header.ForeColor = Color.Black;
                }
                if (InvalidControls.Count > 0)
                {
                    foreach (Control c in InvalidControls.Keys)
                    {
                        XtraTabPage tmpTab;
                        tmpTab = InvalidControls[c];
                        if (tmpTab.Name.Equals(xtraTabPageParent.Name) && tmpTab.PageEnabled)
                        {
                            xtraTabPageParent.Appearance.Header.ForeColor = Color.Black;
                            ForceToValidate = true;
                            return;
                        }
                    }
                }
            }
            else
            {
                xtraTabPageParent.Appearance.Header.ForeColor = Color.Red;
            }
            ForceToValidate = true;
        }
        public void SetValidator(Validator validator, Control control)
        {
            RemoveValidator(control);
            validators.Add(control, validator);

            control.Leave +=
            (sender, e) =>
            {
                /*
                 --get validator based on the control
                 --iterate through validation rules of the validator
                   + NOW, actually set the validation rule for the control
                   + Force the validation provider to validate.
                */
                if (ForceToValidate)
                {
                    Control controlNeedValidating = (Control)sender;
                    if (validators.ContainsKey(controlNeedValidating))
                    {
                        Validator v = validators[controlNeedValidating];
                        if (v != null)
                        {
                            v.ControlNeedValidating = controlNeedValidating;
                            if ((controlNeedValidating as TextEdit).Properties.ReadOnly == false)
                            {
                                if (v.Validate())
                                {
                                    XtraTabPage tmpTab;
                                    XtraTabPage xtraTabPageParent = FindXtraTabPageParent(controlNeedValidating);
                                    if (InvalidControls.ContainsKey(controlNeedValidating))
                                    {
                                        InvalidControls.Remove(controlNeedValidating);
                                        if (InvalidControls.Count == 0)
                                        {
                                            xtraTabPageParent.Appearance.Header.ForeColor = Color.Black;
                                        }
                                    }
                                    if (InvalidControls.Count > 0)
                                    {

                                        if (xtraTabPageParent != null)
                                        {
                                            bool isOtherChildError = false;
                                            foreach (Control c in InvalidControls.Keys)
                                            {
                                                tmpTab = InvalidControls[c];
                                                if (tmpTab.Name.Equals(xtraTabPageParent.Name))
                                                {
                                                    isOtherChildError = true;
                                                    break;
                                                }
                                            }
                                            if (isOtherChildError == false)
                                            {
                                                xtraTabPageParent.Appearance.Header.ForeColor = Color.Black;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };
        }

        public void RemoveValidator(Control control)
        {
            if (validators.ContainsKey(control))
            {
                this.dxValidationProvider.RemoveControlError(control);
                validators.Remove(control);
            }
        }

        public void RemoveControlError()
        {
            RemoveTabControlError();
            foreach (Control c in validators.Keys)
            {
                this.dxValidationProvider.RemoveControlError(c);
            }
        }

        private Dictionary<Control, Validator> validators = new Dictionary<Control, Validator>();

        public class Validator
        {
            private DXValidationProvider validationProvider;

            private IList<ValidationRule> validationRules = new List<ValidationRule>();

            public DXValidationProvider ValidationProvider
            {
                set
                {
                    validationProvider = value;
                }
                get
                {
                    return validationProvider;
                }
            }

            private Validator()
            { }

            public Control ControlNeedValidating { get; set; }

            public Validator(DXValidationProvider validationProvider)
            {
                ValidationProvider = validationProvider;
            }

            public bool Validate()
            {
                bool res = false;

                foreach (ValidationRule validationRule in validationRules)
                {
                    validationProvider.SetValidationRule(ControlNeedValidating, validationRule);
                    validationProvider.SetIconAlignment(ControlNeedValidating, ErrorIconAlignment.MiddleRight);
                    res = validationProvider.Validate(ControlNeedValidating);
                    if (!res)
                    {
                        return res;
                    }
                }

                return res;
            }

            public void AddValidationRule(ValidationRule validationRule)
            {
                validationRules.Add(validationRule);
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
        }

        protected virtual void ShowErrorMessage(Exception exception)
        {
            try
            {
                Logger.Error(exception);

                string message = string.Empty;
                if (exception is BusinessException)
                {
                    var ex = exception as BusinessException;
                    if (string.IsNullOrEmpty(ex.ErrorId))
                    {
                        message = ex.Message;
                    }
                    else
                    {
                        message = Messages.GetString(ex.ErrorId);
                    }

                    if (exception is BussinessConflictUpdateException)
                    {
                        DialogResult rs = MessageBox.Show(message, Messages.GetString("Warning"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        if (rs == System.Windows.Forms.DialogResult.OK)
                        {
                            IBaseEntity e = this.GetEntity();
                            if (e == null)
                            {
                                MessageBox.Show(Messages.GetString("OBJECT_NOT_FOUND"));
                                (this as FormEntryBase).New();
                                FocusFirtsControl();
                            }
                            else
                            {
                                Entity = e;
                            }
                        }
                        return;
                    }

                }
                else
                {
                    if (exception.Message.Contains("The DELETE statement conflicted with the REFERENCE constraint"))
                    {
                        message = Messages.GetString("CANNOT_DELETE_REFERENCE_ITEM");
                    }
                    else
                    {
                        message = exception.Message;
                    }
                } 

                FormException.Show(message, exception);
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        /// <summary>
        /// Show an alert message at the bottom right of the screen
        /// </summary>
        /// <param name="message">message want to display</param>
        //protected virtual void ShowSuccessMessage(string message)
        //{
        //    try
        //    {
        //        if (!m_isImporting)
        //        {
        //            ClearStatusMessage();
        //            Image img = Image.FromFile(Constants.MDI_LOGO_FILE_NAME);
        //            Size outputSize = new Size(64, 64);
        //            Bitmap outputBitmap = new Bitmap(outputSize.Width, outputSize.Height);
        //            using (Bitmap tempBitmap = new Bitmap(img))
        //            {
        //                using (Graphics g = Graphics.FromImage(outputBitmap))
        //                {
        //                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //                    // Get the set of points that determine our rectangle for resizing. 
        //                    Point[] corners = { 
        //                new Point(0, 0), 
        //                new Point(outputBitmap.Width, 0), 
        //                new Point(0, outputBitmap.Height) 
        //            };
        //                    g.DrawImage(tempBitmap, corners);
        //                }
        //            }
        //            //alert properties
        //            alert.AutoFormDelay = ConfigurationConstant.NotificationDelay;
        //            alert.Show(this, this.Text, message, outputBitmap);
        //        }
        //    }
        //    catch { }
        //}

        protected virtual void ClearStatusMessage()
        {
        }
        #endregion

        #region Virtual Methods

        protected virtual void FocusFirtsControl()
        {
        }

        protected virtual IBaseEntity Entity
        {
            get;
            set;
        }

        protected virtual IBaseEntity GetEntity()
        {
            throw new Exception("please override function GetEntity");
        }

        /// <summary>
        /// Load and set the Text property for the controls in a Form
        /// </summary>
        protected virtual void LoadLanguage()
        {
            LoadFormText();
            LoadChildControlTexts(this);
            Localizer.Active = new EditorsLocalizer();
        }

        protected virtual void PreSetupProperties(Control control)
        {
            try
            {
                //if (control is PopupBaseEdit)
                //{
                //    (control as PopupBaseEdit).Properties.CloseUpKey = Constants.CLOSEUP_KEY;
                //}
                if ((control is TextEdit) ||
                   (control is ComboBoxEdit) ||
                   (control is DateEdit) ||
                   (control is ButtonEdit))
                {
                    (control as TextEdit).EnterMoveNextControl = true;
                }
                else if (control is XtraTabControl)
                {
                    (control as XtraTabControl).TabStop = false;
                    (control as XtraTabControl).LookAndFeel.UseDefaultLookAndFeel = false;
                    (control as XtraTabControl).LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Style3D;
                    (control as XtraTabControl).AppearancePage.PageClient.BackColor = Constants.BACKGROUND_COLOR;
                    (control as XtraTabControl).AppearancePage.Header.BackColor = Constants.BACKGROUND_COLOR;
                    (control as XtraTabControl).Appearance.BackColor = Constants.BACKGROUND_COLOR;
                }
                else if (control is LayoutControl)
                {
                    (control as LayoutControl).OptionsFocus.EnableAutoTabOrder = false;
                    (control as LayoutControl).AllowCustomizationMenu = false;
                }
                else if (control is GridControl)
                {
                    foreach (GridView item in (control as GridControl).ViewCollection)
                    {
                        item.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;
                        item.OptionsView.ShowGroupPanel = false;
                        item.OptionsCustomization.AllowColumnMoving = false;
                        item.OptionsCustomization.AllowSort = false;
                        item.OptionsCustomization.AllowFilter = false;
                    }
                }
            }
            catch (Exception ex)
            {

                ShowErrorMessage(ex);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Load and set the Text property for the Form
        /// </summary>
        private void LoadFormText()
        {
            this.Text = FormResources.GetString(this.Name);
        }

        /// <summary>
        /// Load and set the Text property for the child controls of a control
        /// </summary>
        /// <param name="parentForm"></param>
        private void LoadChildControlTexts(Control parentForm)
        {
            try
            {
                foreach (Control ctrl in parentForm.Controls)
                {
                    if (ctrl is LabelControl
                      || ctrl is XtraTabPage
                      || ctrl is GroupBox
                      || ctrl is GroupControl
                      || ctrl is Button
                      || ctrl is LinkLabel
                      || ctrl is SimpleButton
                      || ctrl is Panel
                      || ctrl is CheckEdit
                      || ctrl is Label)
                    {
                        string text = FormResources.GetString(this.Name + "." + ctrl.Name);
                        if (!string.IsNullOrEmpty(text))
                            ctrl.Text = text;
                    }
                    else if (ctrl is XtraTabControl)
                    {
                        ActivatePagesOfTabControl(ctrl as XtraTabControl);
                    }
                    else if (ctrl is GridControl)
                    {
                        foreach (GridView view in (ctrl as GridControl).Views)
                        {
                            foreach (GridColumn column in view.Columns)
                            {
                                column.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
                                string text = FormResources.GetString(this.Name + "." + column.Name);
                                if (!string.IsNullOrEmpty(text))
                                {
                                    column.Caption = text;
                                }
                            }
                        }
                    }
                    else if (ctrl is LayoutControl)
                    {
                        foreach (var item in ((LayoutControl)ctrl).Root.Items)
                        {
                            if (item is LayoutControlItem)
                            {
                                LayoutControlItem currentItem = item as LayoutControlItem;
                                string text = FormResources.GetString(this.Name + "." + currentItem.Name);
                                if (!string.IsNullOrEmpty(text))
                                    currentItem.Text = text;
                            }
                            else if (item is LayoutControlGroup)
                            {
                                LayoutControlGroup currentItemGroup = item as LayoutControlGroup;
                                string text = FormResources.GetString(this.Name + "." + currentItemGroup.Name);
                                if (!string.IsNullOrEmpty(text))
                                    currentItemGroup.Text = text;

                                foreach (var i in ((LayoutControlGroup)item).Items)
                                {
                                    if (i is LayoutControlItem)
                                    {
                                        LayoutControlItem currentItem = i as LayoutControlItem;
                                        string textGroup = FormResources.GetString(this.Name + "." + currentItem.Name);
                                        if (!string.IsNullOrEmpty(textGroup))
                                            currentItem.Text = textGroup;
                                    }
                                }
                            }

                        }
                    }
                    else if (ctrl is RadioGroup)
                    {
                        foreach (var item in (ctrl as RadioGroup).Properties.Items)
                        {
                            if (item is RadioGroupItem)
                            {
                                RadioGroupItem currentItem = item as RadioGroupItem;
                                string text = FormResources.GetString(this.Name + "." + currentItem.Value);
                                if (!string.IsNullOrEmpty(text))
                                    currentItem.Description = text;
                            }
                        }
                    }
                    else if (ctrl is MdiClient)
                    {
                        // Set the BackColor of the MdiClient control.
                        (ctrl as MdiClient).BackColor = PMS.Resources.Constants.MDI_BACKGROUND_COLOR;
                        try
                        {
                            this.picLogo.Image = Image.FromFile(PMS.Resources.Constants.MDI_LOGO_FILE_NAME);
                            ctrl.Paint += new PaintEventHandler(PaintClientBackGround);
                            ctrl.SizeChanged += new EventHandler(SizeClientChangeBackGround);
                        }
                        catch { }
                    }

                    if (ctrl.Controls.Count > 0)
                    {
                        LoadChildControlTexts(ctrl);
                    }
                }
            }
            catch (Exception ex)
            {

                ShowErrorMessage(ex);
            }
        }

        private void SizeClientChangeBackGround(object sender, EventArgs e)
        {
            ((MdiClient)sender).Invalidate();
        }

        private void PaintClientBackGround(object sender, PaintEventArgs e)
        {
            MdiClient mc = (MdiClient)sender;
            e.Graphics.Clip = new Region(mc.ClientRectangle);
            if (this.picLogo.Image != null)
            {

                int scrollWidth = System.Windows.Forms.SystemInformation.VerticalScrollBarWidth;
                int x1 = mc.ClientRectangle.X + mc.ClientRectangle.Width - this.picLogo.Image.Width - scrollWidth * 3;
                int y1 = mc.ClientRectangle.Y + mc.ClientRectangle.Height - this.picLogo.Image.Height - scrollWidth * 3;

                e.Graphics.DrawImageUnscaled(this.picLogo.Image, x1, y1);
            }
        }
        private void XtraFormBase_Load(object sender, EventArgs e)
        {
            LoadLanguage();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
        }

        protected void ActivatePagesOfTabControl(XtraTabControl TabControl)
        {
            for (int i = TabControl.TabPages.Count - 1; i >= 0; i--)
            {
                TabControl.SelectedTabPage = TabControl.TabPages[i];
            }
        }
        #endregion

        #region Events

        private Dictionary<string, XtraTabPage> xtraTabPageParents = new Dictionary<string, XtraTabPage>();
        private Dictionary<Control, XtraTabPage> InvalidControls = new Dictionary<Control, XtraTabPage>();

        private void dxValidationProvider_ValidationFailed(object sender, ValidationFailedEventArgs e)
        {
            XtraTabPage xtraTabPageParent = FindXtraTabPageParent(e.InvalidControl);

            if (xtraTabPageParent != null)
            {
                if (!xtraTabPageParents.ContainsKey(xtraTabPageParent.Name))
                {
                    xtraTabPageParents.Add(xtraTabPageParent.Name, xtraTabPageParent);
                }
                xtraTabPageParent.Appearance.Header.ForeColor = Color.Red;

                if (!InvalidControls.ContainsKey(e.InvalidControl))
                {
                    InvalidControls.Add(e.InvalidControl, xtraTabPageParent);
                }
            }
        }

        private void dxValidationProvider_Disposed(object sender, EventArgs e)
        {
            if (xtraTabPageParents != null && xtraTabPageParents.Count > 0)
            {
                foreach (string key in xtraTabPageParents.Keys)
                {
                    xtraTabPageParents[key].Appearance.Header.ForeColor = Color.Black;
                }
                xtraTabPageParents = new Dictionary<string, XtraTabPage>();
            }
        }

        private XtraTabPage FindXtraTabPageParent(Control control)
        {
            if (control is XtraTabPage)
                return control as XtraTabPage;
            else if (control is BaseForm)
                return null;
            else
                return FindXtraTabPageParent(control.Parent);
        }

        private void RemoveTabControlError()
        {
            if (xtraTabPageParents != null && xtraTabPageParents.Count > 0)
            {
                foreach (string key in xtraTabPageParents.Keys)
                {
                    xtraTabPageParents[key].Appearance.Header.ForeColor = Color.Black;
                }
            }
        }

        public bool ChangeTabPage(Form parent)
        {
            if (parent == this.ParentForm)
            {
                Control activeControl = this.ActiveControl;
                XtraTabPage tabPage = FindXtraTabPageParent(activeControl);
                XtraTabControl tabControl = (tabPage == null) ? null : tabPage.TabControl;
                tabControl = (tabControl != null) ? tabControl :
                                 ((activeControl is XtraTabControl) ? activeControl as XtraTabControl : null);
                if (tabControl != null)
                {
                    tabControl.Focus();
                    int selectedTabIndex = tabControl.SelectedTabPageIndex;
                    if (selectedTabIndex < tabControl.TabPages.Count - 1)
                    {
                        tabControl.SelectedTabPageIndex = selectedTabIndex + 1;
                    }
                    else
                    {
                        tabControl.SelectedTabPageIndex = 0;
                    }
                    return true;
                }
            }
            return false;
        }

        #endregion

    }
}